package controller

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	jsoniter "github.com/json-iterator/go"
	"log"
	"server/acgnovel-go/src/dao"
	"server/acgnovel-go/src/entity"
	"server/acgnovel-go/src/helper"
	"server/acgnovel-go/src/utils"
)

func Login() gin.HandlerFunc {
	return func(c *gin.Context) {
		username := c.Query("username")
		fmt.Println(username)
		if username == "" {
			utils.ResultFail(c, "账号不能为空！")
			return
		}
		password := c.Query("password")
		if password == "" {
			utils.ResultFail(c, "密码不能为空！")
			return
		}
		user := dao.GetUser(username)
		if user == (entity.Users{}) {
			utils.ResultFail(c, "账号不存在")
			return
		}
		if user.Password != password {
			utils.ResultFail(c, "密码错误")
			return
		}
		token := uuid.New().String()
		get := helper.RedisHelperGet(username)
		if get != "" {
			token = get
		}
		helper.RedisHelperSet(username, token, 60*60*8) //8小时
		user.Password = ""
		marshal, err := jsoniter.Marshal(user)
		if err != nil {
			log.Println("error: ", err)
		}
		helper.RedisHelper().Do(context.Background(), "set", token, marshal)
		helper.RedisHelper().Do(context.Background(), "EXPIRE", token, 60*60*8)

		utils.ResultOkData(c, "登陆成功！", gin.H{
			"token": token,
		})
	}
}
